/*
 * @Author: zwz
 * @Date: 2023-05-25 16:30:13
 * @LastEditors: zwz
 * @LastEditTime: 2023-06-06 20:11:24
 * @Description: 请填写简介
 */
const { Service } = require('egg');
const bcrypt = require('bcryptjs');
class UserService extends Service {
  async find() {
    // 假如 我们拿到用户 id 从数据库获取用户详细信息
    // const user = await this.app.mysql.get('users', { id: 11 });
    // console.log(this.app, 'app');
    const user = '1111';
    return { user };
  }
  async checkUserName(query) {
     const {username}  = query
     const users = await this.ctx.model.User.findAll({
        attributes: [ 'username' ],
        where: { username },
      });
      return users;
  }
  async Rigist(body) {
    const { username, password, age} = body;
    // 对密码加密
    const hash = bcrypt.hashSync(password, this.config.bcrypt.saltRounds);
    const user = await this.ctx.model.User.create({ username, password: hash, age: age});
    return user;
  }
  async Login(body) {
    const { username, password } = body;
    const user = await this.ctx.model.User.findOne({
        where: { username },
      });
    if (!user) return false;
    const match = await bcrypt.compare(password, user.password);
    if (match) {
      const { id, username } = user;
      return username
    //   // 获取jwt配置
    //   const { jwt: { secret, expiresIn } } = this.app.config;
    //   // 生成token
    //   const token = this.app.jwt.sign({
    //     id, userName,
    //   }, secret, { expiresIn });
    //   return { userName, token };
    }
    return false
  }
}

module.exports = UserService;
